package mof.gov.dmdc.model.applicationmodule.common;

import oracle.jbo.AttributeDef;
import oracle.jbo.AttributeHints;
import oracle.jbo.Row;
import oracle.jbo.ViewCriteria;
import oracle.jbo.ViewCriteriaRow;
import oracle.jbo.ViewObject;
import oracle.jbo.domain.Date;
import oracle.jbo.server.ApplicationModuleImpl;
import oracle.jbo.server.AttributeDefImpl;
import oracle.jbo.server.SQLBuilder;
import oracle.jbo.server.ViewDefImpl;
import oracle.jbo.server.ViewObjectImpl;
// ---------------------------------------------------------------------
// ---    File generated by Oracle ADF Business Components Design Time.
// ---    Fri Sep 23 13:58:20 ICT 2011
// ---    Custom code may be added to this class.
// ---    Warning: Do not modify method signatures of generated methods.
// ---    Modified by Nguyen Trong Cuong (ntcuong1@cmc.com.vn)
// ---------------------------------------------------------------------
public class CommonModuleImpl extends ApplicationModuleImpl {
    private String ADDRESS_SEARCH_VIEW_OBJECT = "mof.gov.dmdc.model.viewobject.common.searchVO";
    private String ADDRESS_HISTORY_VIEW_OBJECT = "mof.gov.dmdc.model.viewobject.common.namSearchVO";
    protected boolean DETAIL = true;
    protected boolean MATTER = false;
    protected Long countVO;

    /**
     * This is the default constructor (do not remove).
     */
    public CommonModuleImpl() {
    }

    /**
     * Container's getter for orderClauseVO.
     * @return orderClauseVO
     */
    public ViewObjectImpl getorderClauseVO() {
        return (ViewObjectImpl)findViewObject("orderClauseVO");
    }

    /**
     * Container's getter for tableDicVO.
     * @return tableDicVO
     */
    public ViewObjectImpl gettableDicVO() {
        return (ViewObjectImpl)findViewObject("tableDicVO");
    }

    /**
     * Container's getter for searchVO.
     * @return searchVO
     */
    public ViewObjectImpl getsearchVO() {
        return (ViewObjectImpl)findViewObject("searchVO");
    }


    /**
     * Container's getter for searchDefVO.
     * @return searchDefVO
     */
    public ViewObjectImpl getsearchDefVO() {
        return (ViewObjectImpl)findViewObject("searchDefVO");
    }

    /**
     * Container's getter for namSearchVO.
     * @return namSearchVO
     */
    public ViewObjectImpl getnamSearchVO() {
        return (ViewObjectImpl)findViewObject("namSearchVO");
    }

    /**
     * Get the order clause for sqlClause of search View, if the return is "invisible" then correspond the table will not shown;
     * @param tableName String table name in databaase
     * @return String order clause
     */
    public String getOrderClause(String tableName) {
        String returnString = null;
        ViewObject vo = getorderClauseVO();
        vo.setNamedWhereClauseParam("tableName", tableName);
        vo.executeQuery();
        if (vo.hasNext()) {
            Row row = vo.next();
            if (row != null) {
                try {
                    returnString = row.getAttribute("OrderField").toString();
                } catch (Exception e) {
                    returnString = "";
                }
            }
        } else {
            returnString = "invisible";
        }
        return returnString;
    }

    /**
     * create meta viewobject for search,export,and searchDef  viewobject
     * @param tableName
     */
    private ViewObject initTableDicVO(String tableName) {
        ViewObject vo = gettableDicVO();
        vo.setNamedWhereClauseParam("tableName", tableName);
        vo.executeQuery();
        return vo;
    }

    protected void createSearchDefForTableName(String tableName) {
        ViewObject vo = getsearchDefVO();
        ViewCriteria criteria = vo.createViewCriteria();
        ViewCriteriaRow criteriaRow = criteria.createViewCriteriaRow();
        criteriaRow.setAttribute("TableName", tableName);
        criteriaRow.getOperator("=");
        criteria.addRow(criteriaRow);
        vo.applyViewCriteria(criteria);
        vo.executeQuery();
        vo.clearCache();
    }

    protected void createExportDefForTableName(String tableName) {
        ViewObject vo = getexportDEFVO();
        ViewCriteria criteria = vo.createViewCriteria();
        ViewCriteriaRow criteriaRow = criteria.createViewCriteriaRow();
        criteriaRow.setAttribute("TableName", tableName);
        criteriaRow.getOperator("=");
        criteria.addRow(criteriaRow);
        vo.applyViewCriteria(criteria);
        vo.executeQuery();
        vo.clearCache();
    }

    /**
     * create View Object at runtime , if isHistory = true? Matter View : Detail View
     * @param tableName
     * @param metaTableName
     * @param isDetail
     */
    public void createViewObjectForSearch(String tableName, String metaTableName, boolean isDetail) {
        String orderByClause = getOrderClause(metaTableName);
        String selectClause = "";
        boolean includeValid = false;
        boolean includeId = false;
        boolean includeID_BC = false;
        boolean includeID_CT = false;
        ViewDefImpl viewDef;
        viewDef = isDetail ? new ViewDefImpl(ADDRESS_HISTORY_VIEW_OBJECT) : new ViewDefImpl(ADDRESS_SEARCH_VIEW_OBJECT);
        ViewObject vo = initTableDicVO(metaTableName);

        while (vo.hasNext()) {
            Row metaRow = vo.next();
            String colName = metaRow.getAttribute("ColName").toString();
            String colType = metaRow.getAttribute("ColType").toString();
            String colLabel = null;
            try {
                colLabel = metaRow.getAttribute("LabelDisp").toString();
            } catch (Exception e) {
                colLabel = colName;
            }            
            Integer colLength = 0;
            try {
                colLength = (Integer)metaRow.getAttribute("ColLength");
            } catch (Exception e) {
                colLength = 60;
            }     
            Integer colDisp = 0;
            try {
                colDisp = (Integer)metaRow.getAttribute("DefDisp");
            } catch (Exception e) {
                colDisp = 0;
            }
            int colTypeInt = colType.equalsIgnoreCase("number") ? 1 : (colType.equalsIgnoreCase("date") ? 2 : 3);
            selectClause += colName + ",";
            if (colName.equalsIgnoreCase("id"))
                includeId = true;
            if (colName.equalsIgnoreCase("valid"))
                includeValid = true;
            if (colName.equalsIgnoreCase("id_bc"))
                includeID_BC = true;
            if (colName.equalsIgnoreCase("id_ct"))
                includeID_CT = true;
            
            AttributeDefImpl attrDef;
            
            switch (colTypeInt) {
            case 1:
                attrDef = viewDef.addViewAttribute(colName, colLabel, Number.class);
                attrDef.setProperty(AttributeHints.ATTRIBUTE_LABEL, colLabel);
                if (colDisp == 0){
                    attrDef.setProperty(AttributeHints.ATTRIBUTE_DISPLAY_HINT, AttributeHints.ATTRIBUTE_DISPLAY_HINT_HIDE);    
                }
                attrDef.setProperty(AttributeHints.FMT_FORMATTER, "oracle.jbo.format.DefaultNumberFormatter");
                attrDef.setUpdateableFlag(AttributeDef.READONLY);
                break;
            case 2:
                attrDef = viewDef.addViewAttribute(colName, colLabel, Date.class);
                attrDef.setProperty(AttributeHints.ATTRIBUTE_LABEL, colLabel);
                if (colDisp == 0){
                    attrDef.setProperty(AttributeHints.ATTRIBUTE_DISPLAY_HINT, AttributeHints.ATTRIBUTE_DISPLAY_HINT_HIDE);    
                }
                attrDef.setProperty(AttributeHints.FMT_FORMAT, "dd/MM/yyyy");
                attrDef.setProperty(AttributeHints.FMT_FORMATTER, "oracle.jbo.format.DefaultDateFormatter");
                attrDef.setUpdateableFlag(AttributeDef.READONLY);
                break;
            default:
                attrDef = viewDef.addViewAttribute(colName, colLabel, String.class);
                attrDef.setProperty(AttributeHints.ATTRIBUTE_LABEL, colLabel);
                if (colDisp == 0){
                    attrDef.setProperty(AttributeHints.ATTRIBUTE_DISPLAY_HINT, AttributeHints.ATTRIBUTE_DISPLAY_HINT_HIDE);    
                }
                attrDef.setUpdateableFlag(AttributeDef.READONLY);
                break;
            }
            // TODO: Continue... code about col_length
            attrDef.setProperty(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, colLength);
            if (colName.equalsIgnoreCase("ID") || colName.equalsIgnoreCase("cap") || colName.equalsIgnoreCase("ma") || colName.equalsIgnoreCase("ma_nv")) {
                //attrDef.setProperty(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, 40);
                attrDef.setPrimaryKey(true);
                attrDef.setUpdateableFlag(AttributeDef.READONLY);
            } /* else {
                    if (colName.equalsIgnoreCase("ten") || colName.equalsIgnoreCase("ten_nv")) {
                        if (colName.equalsIgnoreCase("ten")) {
                            attrDef.setProperty(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, 340);
                        } else
                            attrDef.setProperty(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, 270);
                    } else {
                        if (isDetail) {
                            attrDef.setProperty(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, 80);
                        } else
                            attrDef.setProperty(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, 120);
                    }
                } */

        }
        if (!includeId && !metaTableName.equalsIgnoreCase("DB_DTNT") && !metaTableName.equalsIgnoreCase("DM_MST_CANHAN")) {
            AttributeDefImpl attrDef;
            attrDef = viewDef.addViewAttribute("ID", "ID", Number.class);
            attrDef.setProperty(AttributeHints.ATTRIBUTE_DISPLAY_HINT, AttributeHints.ATTRIBUTE_DISPLAY_HINT_HIDE);
            attrDef.setProperty(AttributeHints.FMT_FORMATTER, "oracle.jbo.format.DefaultNumberFormatter");
            attrDef.setProperty(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, 40);
            attrDef.setPrimaryKey(true);
            attrDef.setUpdateableFlag(AttributeDef.READONLY);
            selectClause += "ID,";
        }
        if (!includeValid && !isDetail && !tableName.equalsIgnoreCase("db_chitieu") && !metaTableName.equals("DB_DTNT") &&
            !metaTableName.equalsIgnoreCase("DM_MST_CANHAN")) {
            AttributeDefImpl attrDef;
            attrDef = viewDef.addViewAttribute("VALID", "VALID", Number.class);
            attrDef.setProperty(AttributeHints.ATTRIBUTE_DISPLAY_HINT, AttributeHints.ATTRIBUTE_DISPLAY_HINT_HIDE);
            attrDef.setProperty(AttributeHints.ATTRIBUTE_LABEL, "Hiệu lực");
            attrDef.setProperty(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, 110);
            attrDef.setProperty(AttributeHints.FMT_FORMATTER, "oracle.jbo.format.DefaultNumberFormatter");
            attrDef.setUpdateableFlag(AttributeDef.READONLY);
            selectClause += "VALID,";
        }
        if (isDetail && tableName.equalsIgnoreCase("db_chitieu") && !includeID_BC) {
            AttributeDefImpl attrDef;
            attrDef = viewDef.addViewAttribute("ID_BC", "ID_BC", Number.class);
            attrDef.setProperty(AttributeHints.ATTRIBUTE_DISPLAY_HINT, AttributeHints.ATTRIBUTE_DISPLAY_HINT_HIDE);
            attrDef.setProperty(AttributeHints.FMT_FORMATTER, "oracle.jbo.format.DefaultNumberFormatter");
            attrDef.setProperty(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, 40);
            attrDef.setPrimaryKey(true);
            attrDef.setUpdateableFlag(AttributeDef.READONLY);
            selectClause += "ID_BC,";
        }
        if (isDetail && tableName.equalsIgnoreCase("DB_CONGTHUC") && !includeID_CT) {
            AttributeDefImpl attrDef;
            attrDef = viewDef.addViewAttribute("ID_CT", "ID_CT", Number.class);
            attrDef.setProperty(AttributeHints.ATTRIBUTE_DISPLAY_HINT, AttributeHints.ATTRIBUTE_DISPLAY_HINT_HIDE);
            attrDef.setProperty(AttributeHints.FMT_FORMATTER, "oracle.jbo.format.DefaultNumberFormatter");
            attrDef.setProperty(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, 40);
            attrDef.setPrimaryKey(true);
            attrDef.setUpdateableFlag(AttributeDef.READONLY);
            selectClause += "ID_CT,";
        }
        selectClause = selectClause.substring(0, selectClause.length() - 1);
        if (orderByClause.equalsIgnoreCase("invisible")) {
            viewDef.setQuery("SELECT " + selectClause + " FROM " + tableName + " WHERE 1=0");
        } else {
            if (!orderByClause.isEmpty() && orderByClause != "" && orderByClause != null) {
                viewDef.setQuery("SELECT " + selectClause + " FROM " + tableName + " ORDER BY " + orderByClause);
            } else {
                viewDef.setQuery("SELECT " + selectClause + " FROM " + tableName);
            }
        }
        //viewDef.setMaxFetchSize(50);
        viewDef.setFullSql(true);
        viewDef.setBindingStyle(SQLBuilder.BINDING_STYLE_ORACLE_NAME);
        viewDef.resolveDefObject();
        viewDef.registerDefObject();
        if (!isDetail) {
            if (findViewObject("searchVO") != null)
                findViewObject("searchVO").remove();
            viewDef.setFetchSize((byte)23);
            viewDef.setAccessMode(ViewObject.SCROLLABLE);
            viewDef.setRangeSize(20);
            ViewObject searchVO = createViewObject("searchVO", viewDef);
            searchVO.setQueryMode(ViewObject.QUERY_MODE_SCAN_DATABASE_TABLES);
            searchVO.setQueryOptimizerHint("FIRST_ROWS");
            if (includeValid) {
                ViewCriteria criteria = searchVO.createViewCriteria();
                ViewCriteriaRow criteriaRow = criteria.createViewCriteriaRow();
                criteriaRow.setAttribute("VALID", "1");
                criteriaRow.setOperator("VALID", "=");
                criteria.add(criteriaRow);
                searchVO.applyViewCriteria(criteria);
                searchVO.executeQuery();
            }
        } else {
            if (findViewObject("namSearchVO") != null)
                findViewObject("namSearchVO").remove();
            viewDef.setAccessMode(ViewObject.SCROLLABLE);
            viewDef.setRangeSize(20);
            ViewObject searchVO = createViewObject("namSearchVO", viewDef);
            searchVO.setQueryMode(ViewObject.QUERY_MODE_SCAN_DATABASE_TABLES);
        }
    }

    public void createSimpleViewObjectForSearch(String tableName, String metaTableName, boolean isDetail) {
        String orderByClause = getOrderClause(metaTableName);
        String selectClause = "";
        boolean includeValid = false;
        ViewDefImpl viewDef;
        viewDef = isDetail ? new ViewDefImpl(ADDRESS_HISTORY_VIEW_OBJECT) : new ViewDefImpl(ADDRESS_SEARCH_VIEW_OBJECT);
        ViewObject vo = initTableDicVO(metaTableName);

        while (vo.hasNext()) {
            Row metaRow = vo.next();
            String colName = metaRow.getAttribute("ColName").toString();
            String colType = metaRow.getAttribute("ColType").toString();
            String colLabel = metaRow.getAttribute("LabelDisp").toString();
            Integer colLength = 0;
            try {
                colLength = (Integer)metaRow.getAttribute("ColLength");
            } catch (Exception e) {
                colLength = 60;
            }
            Integer colDisp = 0;
            try {
                colDisp = (Integer)metaRow.getAttribute("DefDisp");
            } catch (Exception e) {
                colDisp = 0;
            }
            int colTypeInt = colType.equalsIgnoreCase("number") ? 1 : (colType.equalsIgnoreCase("date") ? 2 : 3);
            selectClause += colName + ",";

            if (colName.equalsIgnoreCase("valid"))
                includeValid = true;
            AttributeDefImpl attrDef;            
            
            switch (colTypeInt) {
            case 1:
                attrDef = viewDef.addViewAttribute(colName, colName, Number.class);
                attrDef.setProperty(AttributeHints.ATTRIBUTE_LABEL, colLabel);
                if (colDisp == 0){
                    attrDef.setProperty(AttributeHints.ATTRIBUTE_DISPLAY_HINT, AttributeHints.ATTRIBUTE_DISPLAY_HINT_HIDE);    
                }                    
                attrDef.setProperty(AttributeHints.FMT_FORMATTER, "oracle.jbo.format.DefaultNumberFormatter");
                attrDef.setUpdateableFlag(AttributeDef.READONLY);
                break;
            case 2:
                attrDef = viewDef.addViewAttribute(colName, colName, Date.class);
                attrDef.setProperty(AttributeHints.ATTRIBUTE_LABEL, colLabel);
                if (colDisp == 0){
                    attrDef.setProperty(AttributeHints.ATTRIBUTE_DISPLAY_HINT, AttributeHints.ATTRIBUTE_DISPLAY_HINT_HIDE);    
                } 
                attrDef.setProperty(AttributeHints.FMT_FORMAT, "dd/MM/yyyy");
                attrDef.setProperty(AttributeHints.FMT_FORMATTER, "oracle.jbo.format.DefaultDateFormatter");
                attrDef.setUpdateableFlag(AttributeDef.READONLY);
                break;
            default:
                attrDef = viewDef.addViewAttribute(colName, colName, String.class);
                attrDef.setProperty(AttributeHints.ATTRIBUTE_LABEL, colLabel);
                if (colDisp == 0){
                    attrDef.setProperty(AttributeHints.ATTRIBUTE_DISPLAY_HINT, AttributeHints.ATTRIBUTE_DISPLAY_HINT_HIDE);    
                } 
                attrDef.setUpdateableFlag(AttributeDef.READONLY);
                break;
            }
            attrDef.setProperty(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, colLength);
            if (colName.equalsIgnoreCase("ID") || colName.equalsIgnoreCase("cap") || colName.equalsIgnoreCase("ma") || colName.equalsIgnoreCase("ma_nv")) {
                attrDef.setPrimaryKey(true);
                attrDef.setUpdateableFlag(AttributeDef.READONLY);
            }
        }
        if (!includeValid && !isDetail && !tableName.equalsIgnoreCase("db_chitieu")) {
            AttributeDefImpl attrDef;
            attrDef = viewDef.addViewAttribute("VALID", "VALID", Number.class);
            attrDef.setProperty(AttributeHints.ATTRIBUTE_DISPLAY_HINT, AttributeHints.ATTRIBUTE_DISPLAY_HINT_HIDE);
            attrDef.setProperty(AttributeHints.ATTRIBUTE_LABEL, "Hiệu lực");
            attrDef.setProperty(AttributeHints.ATTRIBUTE_CTL_DISPLAYWIDTH, 110);
            attrDef.setProperty(AttributeHints.FMT_FORMATTER, "oracle.jbo.format.DefaultNumberFormatter");
            attrDef.setUpdateableFlag(AttributeDef.READONLY);
            selectClause += "VALID,";
        }
        selectClause = selectClause.substring(0, selectClause.length() - 1);
        if (orderByClause.equalsIgnoreCase("invisible")) {
            viewDef.setQuery("SELECT " + selectClause + " FROM " + tableName + "WHERE 1=0");
        } else {
            if (!orderByClause.isEmpty() && orderByClause != "" && orderByClause != null) {
                viewDef.setQuery("SELECT " + selectClause + " FROM " + tableName + " ORDER BY " + orderByClause);
            } else {
                viewDef.setQuery("SELECT " + selectClause + " FROM " + tableName);
            }
        }
        //viewDef.setMaxFetchSize(50);
        viewDef.setFullSql(true);
        viewDef.setBindingStyle(SQLBuilder.BINDING_STYLE_ORACLE_NAME);
        viewDef.resolveDefObject();
        viewDef.registerDefObject();
        if (!isDetail) {
            if (findViewObject("searchVO") != null)
                findViewObject("searchVO").remove();
            viewDef.setFetchSize((byte)23);
            viewDef.setAccessMode(ViewObject.SCROLLABLE);
            viewDef.setRangeSize(20);
            ViewObject searchVO = createViewObject("searchVO", viewDef);
            searchVO.setQueryMode(ViewObject.QUERY_MODE_SCAN_DATABASE_TABLES);
            if (includeValid) {
                ViewCriteria criteria = searchVO.createViewCriteria();
                ViewCriteriaRow criteriaRow = criteria.createViewCriteriaRow();
                criteriaRow.setAttribute("VALID", "1");
                criteriaRow.setOperator("VALID", "=");
                criteria.add(criteriaRow);
                searchVO.applyViewCriteria(criteria);
                searchVO.executeQuery();
            }
        }
    }

    public String getMetaTableName() {
        return "";
    }

    /**
     * Create viewLink for MaterView and DetailView
     */
    public void createViewLinkForDmdc() {
        ViewObject matterVO = getsearchVO();
        ViewObject detailVO = getnamSearchVO();
        createViewLinkBetweenViewObjects("myDynamicViewLink", null, matterVO, new AttributeDef[] { matterVO.findAttributeDef("ID") }, detailVO,
                                         new AttributeDef[] { detailVO.findAttributeDef("ID") }, null);
    }

    public void createViewLinkForDmdc(String matterField, String detailField) {
        ViewObject matterVO = getsearchVO();
        ViewObject detailVO = getnamSearchVO();
        createViewLinkBetweenViewObjects("myDynamicViewLink", null, matterVO, new AttributeDef[] { matterVO.findAttributeDef(matterField) }, detailVO,
                                         new AttributeDef[] { detailVO.findAttributeDef(detailField) }, null);
    }

    /**
     * Container's getter for exportDEFVO.
     * @return exportDEFVO
     */
    public ViewObjectImpl getexportDEFVO() {
        return (ViewObjectImpl)findViewObject("exportDEFVO");
    }

    public void setCountVO(Long coundVO) {
        this.countVO = coundVO;
    }

    public Long getCountVO() {
        if (countVO != null && countVO != 0) {
            ViewObject vo = getsearchVO();
            int ori = vo.getMaxFetchSize();
            vo.setMaxFetchSize(-1);
            vo.executeQuery();
            vo.clearCache();
            countVO = vo.getEstimatedRowCount();
            vo.setMaxFetchSize(ori);
            vo.executeQuery();
            vo.clearCache();
        }
        return countVO;
    }

    /**
     * Container's getter for exportChangeVO.
     * @return exportChangeVO
     */
    public ViewObjectImpl getexportChangeVO() {
        return (ViewObjectImpl)findViewObject("exportChangeVO");
    }
}
